//
//  THNetRequest.m
//  THBaseApp
//
//  Created by TryHone on 16/6/3.
//  Copyright © 2016年 TryHone. All rights reserved.
//

#import "JFNetRequestHelper.h"
#import "JFNetBaseInstance.h"
#import "JFStringHelper.h"
#import "JFAFNInstance.h"
#import "NSString+Hash.h"
#import "JFCacheManager.h"
#import "JFLogHelper.h"
#import "JFSocketRocketInstance.h"
#import "JFCocoaAsyncSocketInstance.h"

static NSInteger _isDebug = false;
@implementation JFNetRequestHelper{

}
+ (JFNetRequestHelper *)sharedManager
{
    static JFNetRequestHelper *sharedTHNetRequestHelperManagerInstance = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        sharedTHNetRequestHelperManagerInstance = [[self alloc] init];
    });
    return sharedTHNetRequestHelperManagerInstance;
}
-(instancetype)init{
    self=[super init];
    if (self) {
    }
    return self;
}

-(void)requestWithRequestVo:(JFRequestVo*)requestVo callBack:(JFCallBack)callback{
    
   NSString* jsonDataStr = [self parseParamData:requestVo];
    if (!jsonDataStr)
    {
        JFResultVo *resultVo = [[JFResultVo alloc] init];
        resultVo.errorInfo = @"请求数据转换失败";
        resultVo.errorNo=-2;
        callback(resultVo);
        return;
    }
    //设置请求开始时间
    requestVo.beginTime=[[NSDate date]timeIntervalSince1970];
    //设置请求流水号
    if(requestVo.ServiceType == ServiceType_Http){
        requestVo.flowNo=[jsonDataStr md5String];
    }
    JFCachelModel * tempData = nil;
    if(requestVo.flowNo){
        tempData =  [JFCacheManager vauleDataFromCacheWithKey:requestVo.flowNo];
    }
    switch (requestVo.cacheType) {
        case CacheType_Net:
            break;
        case CacheType_CacheOrNet:
        case CacheType_CacheOrNet_Update:{
            //读取缓存中的值
            if (tempData.cachelData) {
                JFResultVo *resultVo = tempData.cachelData;
                resultVo.errorInfo = @"请求成功";
                resultVo.noShowErrorInfo = @"从缓存回调,终止网络请求";
                resultVo.errorNo=0;
                AWDISPATCH_MAIN_THREAD(^{
                    callback(resultVo);
                })
                return ;
            }
        }break;
        case CacheType_CacheAndNet:
        case CacheType_CacheAndNet_Update:{
            if (tempData.cachelData) {
                JFResultVo *resultVo = tempData.cachelData;
                resultVo.errorInfo = @"请求成功";
                resultVo.noShowErrorInfo = @"从缓存回调";
                resultVo.errorNo=0;
                AWDISPATCH_MAIN_THREAD(^{
                    callback(resultVo);
                })
     
            }
        }break;
        default:
            break;
    }
    //发送请求
    id<JFServiceInstanceDelegate> serviceInstance = [JFNetRequestHelper serviceInstanceWithRequestVo:requestVo];
    if(serviceInstance){
        [serviceInstance invoke:requestVo callBack:callback];
    }
}
-(void)cancelAllRequest{
    //清除http协议的所有请求
    id<JFServiceInstanceDelegate> serviceInstance = nil;
    serviceInstance =  (id<JFServiceInstanceDelegate>)[JFAFNInstance  shareInstance];
    if(serviceInstance){
       [serviceInstance clearAllRequest];
    }
    //清除webscoket 请求
    id<JFServiceInstanceDelegate> serviceInstance2 = nil;
    serviceInstance2 =  (id<JFServiceInstanceDelegate>)[JFSocketRocketInstance  shareInstance];
    if(serviceInstance2){
       [serviceInstance2 clearAllRequest];
    }
    
    //清除scoket 请求
    id<JFServiceInstanceDelegate> serviceInstance3 = nil;
    serviceInstance3 =  (id<JFServiceInstanceDelegate>)[JFCocoaAsyncSocketInstance  shareInstance];
    if(serviceInstance3){
        [serviceInstance3 clearAllRequest];
    }
}
-(void)cancelRequest:(JFRequestVo*)requestVo{
    id<JFServiceInstanceDelegate> serviceInstance = nil;
    serviceInstance =  (id<JFServiceInstanceDelegate>)[JFNetRequestHelper  serviceInstanceWithRequestVo:requestVo];
    NSString* jsonDataStr = [self parseParamData:requestVo];
    if(!requestVo.flowNo){//如果没有请求号的根据参数生成
        requestVo.flowNo = [jsonDataStr md5String];
    }
    if(serviceInstance){
         [serviceInstance clearRequest:requestVo.flowNo baseUri:requestVo.baseUri];
    }
}
+(void)cancelRequest:(JFRequestVo*)requestVo{
     [[JFNetRequestHelper sharedManager] cancelRequest:requestVo];
}
+(void)requestWithRequestVo:(JFRequestVo*)requestVo callBack:(JFCallBack)callback{
    [[JFNetRequestHelper sharedManager] requestWithRequestVo:requestVo callBack:callback];
}
+(void)cancelAllRequest{
    [[JFNetRequestHelper sharedManager] cancelAllRequest];
}

//根据请求协议获取网络请求类
+(id<JFServiceInstanceDelegate>)serviceInstanceWithRequestVo:(JFRequestVo*)requestVo{
    
    id<JFServiceInstanceDelegate> serviceInstance = nil;
    
    if ([JFStringHelper isEmpty:requestVo.ServiceName])
    {
        switch (requestVo.ServiceType) {
            case ServiceType_Http:
                serviceInstance =  (id<JFServiceInstanceDelegate>)[JFAFNInstance shareInstance];//返回系统实现的http实现协议
                break;
            case ServiceType_WebSocket:
                serviceInstance =  (id<JFServiceInstanceDelegate>)[JFSocketRocketInstance shareInstance];//返回系统实现的WebSocket实现协议
                break;
            case ServiceType_Socket:
                serviceInstance =  (id<JFServiceInstanceDelegate>)[JFCocoaAsyncSocketInstance shareInstance];//返回系统实现的Socket实现协议
                break;
                
            default:
                serviceInstance =  (id<JFServiceInstanceDelegate>)[JFAFNInstance shareInstance];//返回系统实现的http实现协议
                break;
        }
    }
    else
    {
        Class class = NSClassFromString(requestVo.ServiceName);
        //如果存在实例插件
        if (class)
        {
            if ([class isSubclassOfClass:[JFNetBaseInstance class]])
            {
                SEL shareInstance = NSSelectorFromString(@"shareInstance");
                serviceInstance = [class forwardingTargetForSelector:shareInstance];
            }
            else
            {
                serviceInstance = [[class alloc] init];
            }
        }
    }
    return serviceInstance;
}

-(NSString *)parseParamData:(JFRequestVo *)requestVo
{
    NSMutableString *dataStr = [NSMutableString string];
    @try
    {
        [dataStr appendString:[NSString stringWithFormat:@"%@=%@",@"url",requestVo.url]];
        for (NSString  *key in requestVo.reqParam)
        {
            NSObject *obj = requestVo.reqParam[key];
            NSString *str;
            if ([obj isKindOfClass:[NSDictionary class]] || [obj isKindOfClass:[NSMutableDictionary class]])
            {
                NSData *data  = [NSJSONSerialization dataWithJSONObject:obj options:NSJSONWritingPrettyPrinted error:nil];
                str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                str = [NSString stringWithFormat:@"%@=%@&",key,str];
            }
            else
            {
                str = [NSString stringWithFormat:@"%@=%@&",key,requestVo.reqParam[key]];
            }
            [dataStr  appendString:str];
        }
        
        
    }
    @catch (NSException *exception)
    {
        [JFLogHelper stringSyncWriteLogToConsole:[NSString stringWithFormat:@"=====请求数据解析异常%@",exception.description]];
        return nil;
    }
    return dataStr;
}

//同步请求
-(JFResultVo*_Nullable)syncRequestWithRequestVo:(JFRequestVo*_Nonnull)requestVo{
    if(!requestVo){
        return [[JFResultVo alloc] init];
    }
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    __block JFResultVo* data = nil;
    requestVo.isBackInMain = NO;
    [self requestWithRequestVo:requestVo callBack:^(JFResultVo *resultVo) {
        data = resultVo;
        dispatch_semaphore_signal(semaphore);
    }];
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    return data;
}
//同步请求
+(JFResultVo*_Nullable)syncRequestWithRequestVo:(JFRequestVo*_Nonnull)requestVo{
    return  [[JFNetRequestHelper sharedManager] syncRequestWithRequestVo:requestVo];
}

+(void)setIsDebug:(BOOL)isDebug{
    _isDebug = isDebug;
}
+(BOOL)isDebug{
    return  _isDebug;
}

@end
